import { TreeSelect } from 'antd'
import { useEffect, useState } from 'react'
import { getTypeTree } from '@/api/type-tree.js'

const TypeTreeSelect = ({ typeCode, value, onChange, style }) => {
  const fieldNames = {
    label: 'name',
    value: 'id',
    children: 'children',
  }

  const [typeTreeData, setTypeTreeData] = useState([])
  const requestTypeTree = () => {
    getTypeTree({ typeCode }).then((res) => {
      setTypeTreeData(res.data)
    })
  }

  useEffect(() => {
    requestTypeTree()
  }, [ typeCode ])

  return (
    <TreeSelect
      fieldNames={fieldNames}
      showSearch={true}
      checkable={true}
      style={style || {
        width: '100%',
      }}
      dropdownStyle={{
        maxHeight: 300,
        overflow: 'auto',
      }}
      placeholder="请选择"
      allowClear={true}
      treeDefaultExpandAll={true}
      treeData={typeTreeData}
      value={value}
      onChange={onChange}
    />
  )
}

TypeTreeSelect.displayName = 'TypeTreeSelect'

export default TypeTreeSelect
